/*
 * Created on 2008-06-06
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package elka.isi.operator;

import org.evolvica.core.IIndividual;
import org.evolvica.core.IIndividualSet;
import org.evolvica.core.ISetIterator;
import org.evolvica.core.IndividualList;

import elka.isi.individual.RabbitIndividual;
import elka.isi.operator.SortedEcosystem;
import elka.isi.util.RWUtils;

/**
 * @author jurek
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class HarvestingEcosystem extends SortedEcosystem {

	private int carrotAvailable;
	private int rabbitAppetite;
	/* (non-Javadoc)
	 * @see org.evolvica.core.population.IPopulation#insert(org.evolvica.core.IIndividualSet)
	 */
	public IIndividualSet insert(IIndividualSet iset) {
		{
			// if there are no herbivores return rest immidiately
			if(RWUtils.getRabbits(iset).size() == 0)
			{
				return iset;
			}
			
			// putting herbivores into sorted population
			rabbitsPopulation.getFilter().insert(
							this,
							RWUtils.getRabbits(iset));
							
			//RWUtils.printIndividualSet(rabbitsPopulation);
			int carrotEaten = 0;
			int herbivoresFeeded = 0;
			IIndividual individual;
			IIndividualSet setToRemove = new IndividualList();
			for(ISetIterator it = rabbitsPopulation.iterator();it.hasNext();)
			{
				individual = it.next();
				if(carrotEaten < carrotAvailable)
				{
					if (individual instanceof RabbitIndividual) {
						carrotEaten += rabbitAppetite;
						herbivoresFeeded++;
					}
					//TODO dodac obsluge saren tutaj 
				} else
				{
					setToRemove.add(individual);
				}
			}
			
			if(!setToRemove.isEmpty())
			{
				rabbitsPopulation.remove(setToRemove.toArray());
			}
			IIndividualSet toReturn = new IndividualList();
			toReturn.add(rabbitsPopulation.toArray());
			toReturn.add(RWUtils.getWolves(iset).toArray());
			return toReturn;
		}
	}

	/**
	 * @param RABBITS_APETITE
	 */
	public void setRabbitAppetite(int appetite) {
		rabbitAppetite = appetite;		
		
	}

	/**
	 * @param i
	 */
	public void setCarrotAvailable(int i) {
		carrotAvailable = i;
	}

}
